package com.oritsh.dicom.service;

import com.oritsh.dicom.exception.DicomException;
import com.oritsh.dicom.exception.StoreException;
import com.oritsh.dicom.scu.StoreSCU;
import com.oritsh.dicom.utils.AudioHelper;
import com.oritsh.dicom.utils.ImageHelper;
import com.oritsh.dicom.utils.SCUFactory;

import org.dcm4che.data.Attributes;
import org.dcm4che.io.DicomInputStream;
import org.dcm4che.net.DimseRSP;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-3-22
 * Time: 下午3:52
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */
public class CStoreService {
    SCUFactory scuFactory;

    public Attributes cstore(DicomInputStream inputStream) throws DicomException {
        Attributes attributes = null;
        try (StoreSCU scu = (StoreSCU) scuFactory.createSCU(StoreSCU.class)) {
            scu.addDicomInputStream(inputStream);
            DimseRSP[] rsps = scu.sendAll();
            if (rsps.length == 0)
                attributes = null;
            else {
                DimseRSP rsp = rsps[0];
                while (rsp.next()) {
                    attributes = rsp.getCommand();
                }
            }
        } catch (InterruptedException | IOException e) {
            throw new StoreException(e.getMessage());
        }
        return attributes;
    }

    public Attributes cstore(BufferedImage image, Attributes dataset) throws DicomException, IOException {
        DicomInputStream inputStream = ImageHelper.pic2dcm(image, dataset);
        return cstore(inputStream);
    }
    
    public Attributes cstore(AudioInputStream sound, Attributes dataset) throws DicomException, IOException {
        DicomInputStream inputStream = AudioHelper.audio2dcm(sound, dataset);
        return cstore(inputStream);
    }

    public SCUFactory getScuFactory() {
        return scuFactory;
    }

    public void setScuFactory(SCUFactory scuFactory) {
        this.scuFactory = scuFactory;
    }
}
